package pl.ppsoft.fixlang.common;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

import com.google.gson.Gson;

public class Utils {

	@SuppressWarnings("unchecked")
	public static <T> T getREST( String url, Type type ) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		
		HttpParams params = httpclient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 60000);
		HttpConnectionParams.setSoTimeout(params, 120000);
		
		HttpGet httpget = new HttpGet( url );
		HttpResponse response;
		try {
			response = httpclient.execute( httpget );
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				Reader reader = new InputStreamReader(entity.getContent());
				try {
					Gson gson = new Gson();
					return (T)gson.fromJson(reader, type);
				} finally {
					reader.close();
				}
			}
		} catch (ClientProtocolException e) {
			Log.e("getREST", "There was a protocol based error", e);
			throw e;
		} catch (IOException e) {
			Log.e("getREST", "There was an IO Stream related error", e);
			throw e;
		}

		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T> T postREST( String url, Object json, Type type ) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		
		HttpParams params = httpclient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 60000);
		HttpConnectionParams.setSoTimeout(params, 120000);
		
		HttpPost httppost = new HttpPost( url );
				
		Gson gson = new Gson();
		StringEntity s = new StringEntity(gson.toJson(json));
		s.setContentEncoding("UTF-8");
		s.setContentType("application/json");
		httppost.setEntity(s);		
		
		HttpResponse response;
		try {
			response = httpclient.execute( httppost );
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				Reader reader = new InputStreamReader(entity.getContent());
				try {
					return (T)gson.fromJson(reader, type);
				} finally {
					reader.close();
				}
			}
		} catch (ClientProtocolException e) {
			Log.e("postREST", "There was a protocol based error", e);
			throw e;
		} catch (IOException e) {
			Log.e("postREST", "There was an IO Stream related error", e);
			throw e;
		}

		return null;
	}
	
}
